package com.example.tt_bells_v02;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.widget.Button;
import android.widget.ListView;

import com.devsmart.android.ui.HorizontalListView;

public class ActivityEditDay extends Activity implements OnClickListener, OnDragListener {

	//public ArrayList<SliItem> sli_values = new ArrayList<SliItem>();
	//ListView sli_list;
	//Button btest;
	ListView evlist;
	
	//Bell b1;
	//Bell b2;
	
	AdapterBellTemplate tAdapter;
	AdapterBell bAdapter;
	BellManager bm;
	
	Time selected_day = new Time(Time.getCurrentTimezone());
	
	ServiceConnection sconn;
	boolean bound = false;
	
	Activity selflink = this;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(Tag.TAG, " ActivityEditDay.onCreate");
		
		setContentView(R.layout.activity_edit_day);

		//b1 = new Bell(getBaseContext());
		//b2 = new Bell(getBaseContext());
		
		//btest = (Button)findViewById(R.id.button_test);
		//btest.setOnClickListener(this);
		
		Intent aaa = getIntent();
		int a_day = aaa.getIntExtra("aaa_day", 0);
		int a_month = aaa.getIntExtra("aaa_month", 0);
		int a_year = aaa.getIntExtra("aaa_year", 0);
		selected_day.set(a_day, a_month, a_year);
		
		this.setTitle("Edit bells for date: "+a_day+"."+(a_month+1)+"."+a_year);

		evlist = (ListView) findViewById(R.id.evlist);
		evlist.setOnDragListener(this);
		
		sconn = new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName name) {
				// TODO Auto-generated method stub
				Log.d(Tag.TAG,"Service disconnected from DayEditActivity");
				bm = null;
				bound = false;
			}
			
			@Override
			public void onServiceConnected(ComponentName name, IBinder binder) {
				// TODO Auto-generated method stub
				Log.d(Tag.TAG,"Service connected to DayEditActivity");
				bm = ((BellManager.MyBinder)binder).getService();
				bound = true;
			
				tAdapter = new AdapterBellTemplate(bm.templateHolder);
				
			    HorizontalListView templateview = (HorizontalListView) findViewById(R.id.listview);
				templateview.setAdapter(tAdapter);
				
				bAdapter = new AdapterBell(bm.bellHolder,selected_day);

				evlist.setAdapter(bAdapter);
				bAdapter.alink = selflink;
			}
		};
		
		bindService(new Intent(this, BellManager.class), sconn, 0);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_edit_day, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.mid_clear) {
			Intent aaa = new Intent(evlist.getContext(),ActivityDeleteBell.class);
			aaa.putExtra("edit_type", BellInfo.EDIT_DAY);
			startActivityForResult(aaa, 0);
		}
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		//refresh after exiting from editing activity
		if (bound) {
			tAdapter.notifyDataSetChanged();
			bAdapter.refreshToday();
			bAdapter.notifyDataSetChanged();
		}
	};
	
	@Override 
	protected void onDestroy() {
		super.onDestroy();
		Log.d(Tag.TAG, " ActivityEditDay.onDestroy");
		
		//b1.deactivate();
		//b2.deactivate();
		
		//if (bound) 
			unbindService(sconn);
	};
/*	
	private static String[] dataObjects = new String[]{ "Add New",
		"Eyes Gym", "Drink Pills", "Do Work", "Do Sleep", "Buy Food", "Think", "Do Nothing" };
*/
	@Override
	public void onClick(View v) {
		/*
		if (v.getId() == R.id.button_test) {
			//b1.bell_context = v.getContext();
			b1.alarm_message = "QWERTY";
			b1.alarm_time.setToNow();
			//b1.alarm_time.minute++;
			b1.alarm_time.second+=10;
			//b1.activate();
			
			b2.alarm_message = "ASDFG";
			b2.alarm_time.setToNow();
			b2.alarm_time.second+=15;
			//b2.activate();
		}
		*/
	}	
	//------------------------------------------------------------------------
/*
		private BaseAdapter mAdapter = new BaseAdapter() {

			private OnLongClickListener mOnTemplateLongClick = new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					
					Intent aaa = new Intent(v.getContext(),TemplateEditActivity.class);
					v.getContext().startActivity(aaa);
					
					return false;
				}
			};
					
			
			@Override
			public int getCount() {
				return dataObjects.length;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public long getItemId(int position) {
				return 0;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_in_list, null);
				TextView title = (TextView) retval.findViewById(R.id.title);
				ImageView iv = (ImageView) retval.findViewById(R.id.image);
				if (position == 0) {
					iv.setImageDrawable(getResources().getDrawable(R.drawable.plus));
				}
				//iv.setOnClickListener(mOnButtonClicked);
				iv.setOnLongClickListener(mOnTemplateLongClick);
				//Button button = (Button) retval.findViewById(R.id.clickbutton);
				//button.setOnClickListener(mOnButtonClicked);
				title.setText(dataObjects[position]);
				
				return retval;
			}
			
		};
			
	*/

	@Override
	public boolean onDrag(View v, DragEvent event) {
		int action = event.getAction();
		switch (action) {
			case DragEvent.ACTION_DRAG_STARTED: {
				
			break; }
			case DragEvent.ACTION_DRAG_ENDED: {
				
			break; }
			case DragEvent.ACTION_DRAG_ENTERED: {
				
			break; }
			case DragEvent.ACTION_DRAG_EXITED: {
				
			break; }
			case DragEvent.ACTION_DROP: {
				 View view = (View) event.getLocalState();
				 int pos = Integer.parseInt(view.getTag().toString());
				 insertBellFromTemplate(pos);
			break; }
			default: {
				
			break; }
		}
		return true;
	}
	
	//TODO: make constructor from Template
	public void insertBellFromTemplate(int position_in_holder) {
		BellTemplate bt = bm.templateHolder.get(position_in_holder);
		
		Bell newbell = new Bell(bm.getBaseContext());
		newbell.id = bm.debug_id++;
		newbell.alarm_message = new String(bt.alarm_message);
		newbell.alarm_time.set(selected_day.monthDay, selected_day.month, selected_day.year);
		newbell.alarm_time.allDay = false;
		newbell.last_alarm_time.allDay = false;
		newbell.bell_actions = bt.bell_actions;
		newbell.bell_state = 0;
		newbell.bell_type = bt.bell_type;
		newbell.icon_index = bt.icon_index;
		newbell.name_long = bt.name_long;
		newbell.name_short = bt.name_short;
		newbell.sound_index = bt.sound_index;
		
		switch (newbell.bell_type) {
			case BellInfo.BELL_TYPE_SINGLE: {
				newbell.alarm_time.hour = newbell.getHour(bt.single_alarm_time);
				newbell.alarm_time.minute = newbell.getMinute(bt.single_alarm_time);;
				newbell.alarm_time.second = 0;
			break; }
			case BellInfo.BELL_TYPE_PERIODIC: {
				newbell.period_size = bt.period_size;
				newbell.periods_count = bt.periods_count;
				newbell.alarm_time.hour = newbell.getHour(bt.periodic_alarm_start);
				newbell.alarm_time.minute = newbell.getMinute(bt.periodic_alarm_start);
				newbell.alarm_time.second = 0;
				newbell.recalcTimepoints();
			break; }
			case BellInfo.BELL_TYPE_MULTIPLE: {
				
			break; }
			case BellInfo.BELL_TYPE_RANDOM: {
				
			break; }
		}
		
		//add bell to bm.bellHolder
		bm.bellHolder.add(newbell);
		Log.d(Tag.TAG, "adding new bell");
		bAdapter.refreshToday();
		bAdapter.notifyDataSetChanged();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(Tag.TAG, "real_pos="+requestCode+" , result="+resultCode);
		if (resultCode == RESULT_OK) {
			boolean do_delete = data.getBooleanExtra("delete", false);
			if (do_delete) {
				int edit_type = data.getIntExtra("edit_type", BellInfo.EDIT_BELL);
				if (edit_type == BellInfo.EDIT_DAY) { //Clear all day
					boolean ret = false;
					for (Bell element : bAdapter.todayHolder) {
						ret = bAdapter.bellHolder.remove(element);
						Log.d(Tag.TAG,"Removing bell ret "+ret);
					}
				} else { //Delete bell
					bm.bellHolder.remove(requestCode);
				}
				bAdapter.refreshToday();
				bAdapter.notifyDataSetChanged();
			}
		}
	}
	
}
